package com.baihan.angus.app.game.common.util;

import android.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESUtil {
    private static final String SALT = "9876974121098467";
    private static final String OFFSET = "AreYouOk_LeiBuSi";

    /**
     * AES 加密操作
     *
     * @param encData 待加密内容
     * @param key     加密密钥
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String encData, String key) {
        String basekey = key + SALT;
        basekey = basekey.substring(0, 16);

        try {
            if (basekey == null) {
                return null;
            }
            if (basekey.length() != 16) {
                return null;
            }
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            byte[] raw = basekey.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            IvParameterSpec iv = new IvParameterSpec(OFFSET.getBytes("utf-8"));// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(encData.getBytes("utf-8"));
            return new String(Base64.encode(encrypted, Base64.DEFAULT), "utf-8");
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * AES 解密操作
     *
     * @param sSrc
     * @param key
     * @return
     */
    public static String decrypt(String sSrc, String key) {
        String basekey = key + SALT;
        basekey = basekey.substring(0, 16);
        try {
            byte[] raw = basekey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(OFFSET.getBytes("utf-8"));
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 = Base64.decode(sSrc, Base64.DEFAULT);// 先用base64解密
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, "utf-8");
            return originalString;
        } catch (Exception ex) {
            return null;
        }
    }

}
